package com.learn.security.web.controllers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;
import java.util.Objects;

/**
 * @auther liuhw
 * @date 2020/3/17 13:50
 * @description:
 * @since 1.0
 **/
@Controller
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SessionRegistry registry;

    @GetMapping("/")
    public String showHome() {
//        String name = SecurityContextHolder.getContext().getAuthentication().getName();
//        logger.info("当前登陆用户 {}", name);

        return "home";
    }

    @GetMapping(value = "/admin", produces = "text/plain;charset=utf-8")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public String printAdmin() {
        return "如果你看到这句话, 说明你有ROLE_ADMIN角色";
    }

    @GetMapping(value = "/admin/r", produces = "text/plain;charset=utf-8")
    @ResponseBody
    @PreAuthorize("hasPermission('/admin/r', 'r')")
    public String printAdminR() {
        return "如果你看到这句话, 说明你访问/admin/r具有r权限";
    }

    @GetMapping(value = "/admin/c", produces = "text/plain;charset=utf-8")
    @ResponseBody
    @PreAuthorize("hasPermission('/admin/c', 'c')")
    public String printAdminC() {
        return "如果你看到这句话, 说明你访问/admin/c具有c权限";
    }

    @GetMapping(value = "/user", produces = "text/plain;charset=utf-8")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_USER')")
    public String printUser() {
        return "如果你看到这句话, 说明你有ROLE_USER角色";
    }

    @GetMapping(value = "/login/invalid", produces = "text/plain;charset=utf-8")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String invalid() {
        return "Session 已过期, 请重新登录";
    }

    @GetMapping(value = "/kick", produces = "text/plain;charset=utf-8")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @ResponseBody
    public String removeUserSessionByUsername(@RequestParam String username) {
        int count = 0;

        // 获取session中所有的用户信息
        List<Object> users = registry.getAllPrincipals();
        for (Object principal : users) {
            if (principal instanceof User) {
                if (Objects.equals(((User) principal).getUsername(), username)) {
                    List<SessionInformation> sessionInfo = registry.getAllSessions(principal, false);
                    if (Objects.nonNull(sessionInfo) && !sessionInfo.isEmpty()) {
                        for (SessionInformation info : sessionInfo) {
                            info.expireNow();
                            count++;
                        }
                    }
                }
            }
        }
        return "操作成功, 清理session共 " + count + " 个";
    }
}
